const COS = require("cos-nodejs-sdk-v5");
const cdnClient = require("tencentcloud-sdk-nodejs/tencentcloud/services/cdn/v20180606/cdn_client");
const getHash = require("./hash");
const path = require("path");
const fs = require("fs");
const { config } = require("process");

let mac = null;

let bucketName = "";
let baseUrl = "";
let region = "";

//桶管理器
let bucketManager = null;
//上传管理器
let uploadManager = null;
//CDN管理器
let cdnManager = null;

//获取文件信息
function getFileInfo(name) {
  return new Promise((resolve, reject) => {
    mac.headObject(
      {
        Bucket: bucketName,
        Region: region,
        Key: name,
      },
      (err, data) => {
        const code = err?.statusCode || data?.statusCode;
        if (code == 404) resolve({ ETag: null, code: code });
        else if (err && code !== 404) {
          reject({ code: code, message: err?.message });
        } else {
          resolve({ ETag: data.ETag || null, code: code });
        }
      }
    );
  });
}

//上传一个文件
function uploadFile(name, filePath) {
  return new Promise((resolve, reject) => {
    mac.putObject(
      {
        Bucket: bucketName /* 填入您自己的存储桶，必须字段 */,
        Region: region /* 存储桶所在地域，例如 ap-beijing，必须字段 */,
        Key: name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
        StorageClass: "STANDARD",
        /* 当 Body 为 stream 类型时，ContentLength 必传，否则 onProgress 不能返回正确的进度信息 */
        Body: fs.createReadStream(filePath), // 上传文件对象
        ContentLength: fs.statSync(filePath).size,
      },
      function (err, data) {
        console.log(err, data);
        if (err) reject(err);
        else resolve(data);
      }
    );
  });
}

//刷新缓存
async function refreshFiles(list) {
  try {
    if (!cdnManager) {
      cdnManager = new cdnClient.Client({
        credential: {
          secretId: config.secretId,
          secretKey: config.secretKey,
        },
        region: "ap-guangzhou",
      });
    }
    console.log(cdnManager.PurgeUrlsCache);
    return await cdnManager.PurgeUrlsCache({
      Urls: list,
      cdnPurgeCache: true,
    });
  } catch (error) {
    console.log(error);
  }
}

function init(config) {
  mac = new COS({
    SecretId: config.secretId,
    SecretKey: config.secretKey,
  });
  bucketName = config.bucketName;
  baseUrl = config.baseUrl;
  region = config.region;
}

module.exports = {
  getFileInfo,
  refreshFiles,
  uploadFile,
  getHash,
  init,
  // changeTarget
};
